<template>
  <div >
    <el-container class="subWidth">
      <el-header class='subheader'
                 style="height: 48px; background-color: white; margin: 2px; padding: 2px; border-radius: 5px">
        <el-form :inline="true" class="demo-form-inline" label-position="left" label-width="80px">
          <el-form-item label="知识用户">
            <el-input v-model="searchQuery.name" @keyup.enter="fetchItems"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary"  @click="fetchItems">查询</el-button>
            <el-button type="primary"   @click="resetSearch">重置</el-button>
            <el-button type="primary"  @click="showAddDialog">新增</el-button>
          </el-form-item>
        </el-form>
      </el-header>
      <el-main id="tableContent">
        <el-table :data="knowledge" style="width: 100%" :show-header="true">
          <el-table-column type="selection" width="42" align="center"></el-table-column>
          <el-table-column prop="id" label="编号" width="45" align="center"></el-table-column>
          <el-table-column prop="title" label="标题" width="150" align="center"></el-table-column>
          <el-table-column prop="content" label="内容" width="230" align="center"></el-table-column>
          <el-table-column prop="classification" label="分类" width="170" align="center"></el-table-column>
<!--          <el-table-column label="图片" align="center">
            <template slot-scope="scope">
              <img :src="scope.row.picture" style="width: 80px; height: 50px; object-fit: cover;"/>
            </template>
          </el-table-column>-->
          <el-table-column label="操作" fixed="right" width="200">
            <template slot-scope="scope">
              <el-button type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button   plain type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <!-- 新增/编辑商品对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="400px">
        <div class="el-dialog-div">
          <el-form :model="currentKnowledge" label-width="80px">
            <el-form-item label="标题">
              <el-input v-model="currentKnowledge.title"></el-input>
            </el-form-item>
            <el-form-item label="内容">
              <el-input v-model="currentKnowledge.content"></el-input>
            </el-form-item>
            <el-form-item label="分类">
              <el-input v-model="currentKnowledge.classification"></el-input>
            </el-form-item>
<!--            <el-form-item label="图片">
              <el-input v-model="currentKnowledge.picture"></el-input>
            </el-form-item>-->
          </el-form>
        </div>
<!--        <span slot="footer" class="dialog-footer">-->
<!--      <el-button @click="dialogVisible = false">取消</el-button>-->
<!--      <el-button type="primary" @click="currentKnowledge.id ? updateKnowledge() : saveForm()">保存</el-button>-->
<!--        </span>-->

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveForm">保存</el-button>
         </span>
      </el-dialog>
      <MyPagination :total="total"/>
    </el-container>
  </div>
</template>
<script>
import axios from "axios";
import MyPagination from "@/components/MyPagination.vue";
import '@/assets/add.css'
export default {
  components: {MyPagination},
  data(){
    return{
      searchQuery:{
        title:''
      },
      knowledge:[],
      dialogVisible: false,
      dialogTitle: '新增知识',
      currentKnowledge:{
        id: null,
        title: null,
        content: null,
        classification: null,
        picture: null
      },
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示的条目数
      total: 0, // 总条目数
    }
  },
  methods: {
    handleAvatarSuccess(res) {
      this.currentItem.imgUrl = res.data;
    },
  // 在 methods 中定义的 add 方法，用于打开对话框并设置标题
  add(id) {
    this.dialogVisible = true;
    this.resetForm();
    if (id) {
      this.dialogTitle = '编辑商品';
      // 假设 findItemById 是一个方法，用于根据 ID 查询商品详情
      this.findItemById(id);
    } else {
      this.dialogTitle = '新增商品';
    }
  },
  // 用于打开新增商品对话框的方法
  showAddDialog() {
    this.dialogVisible = true; // 设置对话框为可见
    this.resetForm(); // 重置表单
    this.dialogTitle = '新增知识'; // 设置对话框标题为“新增商品”
  },
  resetForm(){
    this.currentKnowledge = {
      id: null,
      title: '',
      content: '',
      classification: '',
   /*   picture: null*/
    }
  },
    findItemById(id) {
    // 假设有一个方法来根据ID查询商品详情
    axios.get(`/knowledge/find/${id}`).then(response => {
      this.currentKnowledge = response.data;
    }).catch(error => {
      console.error("Error finding knowledge by id:", error);
    });
  },
  saveForm() {

    /*if (this.currentKnowledge.id) {
      // 执行修改操作
      axios.put("/knowledge/update" ).then(response => {
        // 使用 response 数据
        console.log('Update response:', response.data);
        this.dialogVisible = false;
        this.fetchItems();
        this.$message.success('知识信息更新成功');
      }).catch(error => {
        console.error("Error updating knowledge:", error);
        this.$message.error('知识信息更新失败');
      });
    } else {
      // 执行新增操作
      axios.post("/knowledge/add").then(response => {
        // 使用 response 数据
        console.log('Add response:', response.data);
        this.dialogVisible = false;
        this.fetchItems();
        this.$message.success('知识新增成功');
      }).catch(error => {
        console.error("Error adding knowledge:", error);
        this.$message.error('知识新增失败');
      });
    }*/

    if (this.currentKnowledge.id) {
      // 执行修改操作
      axios.put("/knowledge/update", this.currentKnowledge).then(response => {
        // 使用 response 数据
        console.log('Update response:', response.data);
        this.dialogVisible = false;
        this.fetchItems();
        this.$message.success('知识信息更新成功');
      }).catch(error => {
        console.error("Error updating knowledge:", error);
        this.$message.error('知识信息更新失败');
      });
    } else {
      // 执行新增操作
      axios.post("/knowledge/add", this.currentKnowledge).then(response => {
        // 使用 response 数据
        console.log('Add response:', response.data);
        this.dialogVisible = false;
        this.fetchItems();
        this.$message.success('知识新增成功');
      }).catch(error => {
        console.error("Error adding knowledge:", error);
        this.$message.error('知识新增失败');
      });
    }

  },


  fetchItems() {
    const params = this.searchQuery.title ? {title: this.searchQuery.title} : {};
    axios.get("/knowledge/find", {params}).then(response => {
      this.knowledge = response.data;
    }).catch(error => {
      console.error("Error fetching knowledge:", error);
    });
  },
    resetSearch() {
      this.searchQuery.title = '';
      this.fetchItems(); // 重置后重新获取所有商品列表
    },
  handleEdit(index, row) {
    this.dialogVisible = true; // 打开对话框
    this.dialogTitle = '编辑管理'; // 设置对话框标题
    // 将当前行的数据复制到currentKnowledge ，用于在对话框中显示
    // 确保将 isDelete 和 isRecommed 转换为布尔值
    this.currentKnowledge = {
      ...row,
      isDelete: row.isDelete === 1, // 将 1 转换为 true，0 转换为 false
      isRecommed: row.isRecommed === 1 // 将 1 转换为 true，0 转换为 false
    };
  },
  handleDelete(index, row) {
    axios.delete(`/knowledge/delete/${row.id}`).then(response => {
      // 检查后端返回的响应数据
      if (response.data.success) { // 假设后端返回的数据包含一个 success 字段
        this.knowledge.splice(index, 1);
        this.fetchItems();
        console.log("删除成功")
        this.$message.success('知识删除成功');
      }
    })
  },
  },
  mounted() {
    this.fetchItems(); // 页面加载时获取商品列表
  }
}
</script>

<style scoped>

</style>
